package liuyuyang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import liuyuyang.domain.User;
import liuyuyang.domain.UserRole;
import liuyuyang.mapper.UserRoleMapper;
import liuyuyang.service.UserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {
    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public void auth(Integer uid, List<Integer> uids) {
        userRoleMapper.deleteById(uid);

        for (Integer rid : uids) {
            UserRole userRole = new UserRole();
            userRole.setUserId(uid);
            userRole.setRoleId(rid);

            userRoleMapper.insert(userRole);
        }
    }

    @Override
    public List<User> getUserRoleList(Integer id) {
        return userRoleMapper.getUserRoleList(id);
    }

    @Override
    public void binding(Integer rid, List<Integer> uids) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", rid);

        // 先删除
        userRoleMapper.delete(queryWrapper);

        // 再绑定
        for (Integer id : uids) {
            UserRole userRole = new UserRole();
            userRole.setRoleId(rid);
            userRole.setUserId(id);

            userRoleMapper.insert(userRole);
        }
    }
}
